package com.qf.service.impl;

import com.qf.entity.Student;
import com.qf.service.StudentService;
import com.qf.utils.StudentDataStore;
import org.springframework.stereotype.Service;

import java.util.List;

// 让spring框架在启动过程中，创建这个类的对象
@Service
public class StudentServiceImpl implements StudentService {

    @Override
    public List<Student> add(Student student) {

        // 1. 给学生生成一个 id
        Integer id = StudentDataStore.idgenerator++;
        student.setId(id);

        // 2. 放入list中
        StudentDataStore.stuList.add(student);

        return StudentDataStore.stuList;
    }

    @Override
    public void edit(Student student) {
        // 根据学生的id修改学生数据

        //1. 查找该id在 list中的下标位置
        Integer id = student.getId();
        int index = -1;
        for (int i = 0; i < StudentDataStore.stuList.size(); i++) {
            if (id.equals(StudentDataStore.stuList.get(i).getId())){
                index = i;
                break;
            }
        }
        StudentDataStore.stuList.set(index,student);
    }

    @Override
    public List<Student> list() {
        return StudentDataStore.stuList;
    }

    @Override
    public void delete(Integer id) {

        int index = -1;
        for (int i = 0; i < StudentDataStore.stuList.size(); i++) {
            if (id.equals(StudentDataStore.stuList.get(i).getId())){
                index = i;
                break;
            }
        }
        // 从list中删除指定下标的元素
        StudentDataStore.stuList.remove(index);

    }

    @Override
    public Student findbyId(Integer id) {

        int index = -1;
        for (int i = 0; i < StudentDataStore.stuList.size(); i++) {
            Student student = StudentDataStore.stuList.get(i);
            Integer sutId = student.getId();
            if (sutId.equals(id)){
                index = i;
                break;
            }
        }

        return StudentDataStore.stuList.get(index);
    }
}
